package com.iot.inclinometer.util;

import android.content.Context;

import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.pojo.CorrectDataInfo;
import com.iot.inclinometer.pojo.ObserveInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 导出数据
 * 
 * @author WXR
 * 
 */
public class JXLCreateResult implements Runnable {

	private String _file=null;
	private BaseInfo baseInfo = null;
	private List<ObserveInfo> observeInfosA0=null;
	private List<List<CorrectDataInfo>> correctDataInfoLists=null;
	private Context context = null;
	private FileOutputStream fos = null;
	private WritableWorkbook wwb = null;
	private File fileDir  = null;
	private String filePath = null;
	private File targetFile = null;
	private String[] baseInfoTitles = { "工程名称", "工点名称", "钻孔编号", "孔深", "里程桩号",
			"位置描述", "X坐标", "Y坐标","汇总位移方向"};
	private String[] directTitles = { "A0", "B0", "A180", "B180","θA","θB"};
	private String[] directTitles0x=null;
	private String[] directTitles0y=null;
	
	private String[] Titlesweiyix=null;private String[] Titlesweiyiy=null;
	
	private String[] measureDataTitles=null;
	private String[] dateAndWeatherTitles=null;
	private final String title0="滑动位移汇总曲线";
	private final String directionA="主滑位移";
	private final String directionB="非主滑位移";
	private final String directionAll="合成位移";
	
	public JXLCreateResult(String file,BaseInfo baseInfo,List<ObserveInfo> observeInfosA0,List<List<CorrectDataInfo>> correctDataInfoLists,
			Context context) {
		this._file=file;
		this.baseInfo = baseInfo;
		this.observeInfosA0=observeInfosA0;
		this.correctDataInfoLists=correctDataInfoLists;
		this.measureDataTitles=new String[observeInfosA0.size()+1];
		this.directTitles0x=new String[observeInfosA0.size()+1];
		this.directTitles0y=new String[observeInfosA0.size()+1];
		
		this.Titlesweiyix=new String[observeInfosA0.size()+1];
		this.Titlesweiyiy=new String[observeInfosA0.size()+1];
		this.dateAndWeatherTitles=new String[observeInfosA0.size()];
		
		
		this.context = context;
		initValue();
	}
	
	/**
	 * 初始化数组的值
	 */
	private void initValue() {
		int count=observeInfosA0.size();//观测总次数
		
		//给每次测量编号
		measureDataTitles[0]="孔深(m)";directTitles0x[0]="孔深(m)";directTitles0y[0]="孔深(m)";
		
		Titlesweiyix[0]="孔深(mm)";
		Titlesweiyiy[0]="孔深(mm)";
	
		for(int i=1;i<=count;i++){
			measureDataTitles[i]="第"+i+"次";
			directTitles0x[i]="θA"+i;
			directTitles0y[i]="θB"+i;
			
			Titlesweiyix[i]="位移"+i+"(mm)";Titlesweiyiy[i]="位移"+i+"(mm)";
			
			
		}
		//给dateAndWeatherTitles数组赋值，每次测量的日期+天气
		int j=0;
		for(ObserveInfo observeInfo:observeInfosA0){
			String timeStr=observeInfo.getTime();
			
			String[] time=timeStr.split("-");
			String year=time[0];//年
			String month=time[1];//月
			String[] dayAndTime=time[2].split(" ");
			String day=dayAndTime[0];//日
			
			dateAndWeatherTitles[j]="("+year+"."+month+"."+day;//如：2016.02.20晴
			j++;
		}
	}
	/*
	 * Excel文件生成过程 1.基本信息肯定有，观察信息有A0方向的，修正数据可能无 2.判断数据是否存在，如果不存在，文件命名时加上 NULL 作为命名后缀
	 * 3.多组修正数据保存为一份文件，主滑、非主滑、总方向位移分别在不同的Sheet中
	 * 
	 * 命名规则 --项目名称（文件夹） ----工点名称（文件夹）
	 * ------滑动位移汇总曲线-工程名-工点名-钻孔编号.xls
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {	
		try {
			// 准备设置excel工作表的标题     // 输出的excel的路径
			fileDir = new File(_file+ File.separator + baseInfo.getProjectName()
					+ File.separator + baseInfo.getItemName());
					//通常 File f = new File("F:\\java\\rose"); 参数为字符串格式的路径
					//定义目录，例如_file为/sdcard/baofeng，它整体就是一个字符串，实际上如果把它表示出来，
					//应该是”//sdcard//baofeng”，所以后面还要加File.separator+ProjectName+File.separator+ItemName
					//构成一个完整的路径
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			
			filePath =title0+"-"+baseInfo.getProjectName()+"-"+baseInfo.getItemName()+"-"+baseInfo.getDrillNum()+".xls"; // 定义导出文件
			
			//无论之前是否已存在该文件，都将重新建立一个该文件
			targetFile = new File(fileDir, filePath);
			// 创建Excel工作薄
			
			// 新建立一个jxl文件,即在SDcard盘下生成test.xls
			fos = new FileOutputStream(targetFile);
			wwb = Workbook.createWorkbook(fos);
			// 添加三个工作表并设置每一个Sheet的名字
			WritableSheet sheet1= wwb.createSheet("主滑位移汇总", 0);
			WritableSheet sheet2= wwb.createSheet("非主滑位移汇总", 0);
			WritableSheet sheet3= wwb.createSheet("合成位移汇总", 0);
			// 给每张表添加基本信息
			this.createBaseInfo(sheet1,baseInfoTitles,baseInfo,directionA);
			this.createBaseInfo(sheet2,baseInfoTitles,baseInfo,directionB);
			this.createBaseInfo(sheet3,baseInfoTitles,baseInfo,directionAll);
			//创建测量数据
			Label label;
			for (int i = 0; i < measureDataTitles.length; i++) {
				
				label = new Label((measureDataTitles.length-1)*8+i, 5, directTitles0x[i]);
				// 将定义好的单元格添加到工作表中
				sheet1.addCell(label);
				label = new Label((measureDataTitles.length-1)*8+measureDataTitles.length+1, 4, baseInfo.getDrillNum()+"(孔号)");
				sheet1.addCell(label);
				//weiyi
				label = new Label((measureDataTitles.length-1)*8+i+measureDataTitles.length+1, 5, Titlesweiyix[i]);
				sheet1.addCell(label);
				
				label = new Label((measureDataTitles.length-1)*8+i,5,directTitles0y[i]);
				sheet2.addCell(label);
				label = new Label((measureDataTitles.length-1)*8+measureDataTitles.length+1, 4, baseInfo.getDrillNum()+"(孔号)");
				sheet2.addCell(label);
				//weiyi
				label = new Label((measureDataTitles.length-1)*8+i+measureDataTitles.length+1, 5, Titlesweiyiy[i]);
				sheet2.addCell(label);
				
			}
			//添加日期
			for (int i = 0; i <dateAndWeatherTitles.length; i++) {
				label = new Label((measureDataTitles.length-1)*8+i+measureDataTitles.length+2, 4, dateAndWeatherTitles[i]);
				// 将定义好的单元格添加到工作表中
				sheet1.addCell(label);
				label = new Label((measureDataTitles.length-1)*8+i+measureDataTitles.length+2, 4, dateAndWeatherTitles[i]);
				sheet2.addCell(label);
				label = new Label(i+1, 5, dateAndWeatherTitles[i]);
				sheet3.addCell(label);
			}
			
			//添加"孔深(mm)"两字
			for (int i = 1; i < measureDataTitles.length; i++) {
				label = new Label((i-1)*8, 5, measureDataTitles[0]);
				// 将定义好的单元格添加到工作表中
				sheet1.addCell(label);
				label = new Label((i-1)*8, 5, measureDataTitles[0]);
				sheet2.addCell(label);
				label = new Label(0, 4, measureDataTitles[0]);
				sheet3.addCell(label);
			}
			//添加"第几次"三字、和 "A0", "B0", "A180", "B180","θAi","θBi"列名
			for (int i = 1; i < measureDataTitles.length; i++) {				
				label = new Label((i-1)*8+1, 4, measureDataTitles[i]);				
				sheet1.addCell(label);
				for (int i1 = 0; i1 < directTitles.length; i1++) {
					label = new Label((i-1)*8+1+i1, 5, directTitles[i1]);
					sheet1.addCell(label);
				}
				
				label = new Label((i-1)*8+1, 4, measureDataTitles[i]);
				sheet2.addCell(label);
				for (int i1 = 0; i1 < directTitles.length; i1++) {
					label = new Label((i-1)*8+1+i1, 5, directTitles[i1]);
					sheet2.addCell(label);
				}
				
				label = new Label(i, 4, measureDataTitles[i]);
				sheet3.addCell(label);
			}
			int i=1;
			for(List<CorrectDataInfo> correctDataInfos :correctDataInfoLists){
				//如果该次观测，存在修正数据，导出数据
				if(correctDataInfos.size()>0){
					int length = correctDataInfos.size();
					double[] depths = new double[length];//深度
					double[] cerrors = new double[length];
					double[] A0 = new double[length];
					double[] B0 = new double[length];
					double[] A180 = new double[length];
					double[] B180 = new double[length];
					double[] θAi = new double[length];
					double[] θBi = new double[length];					
					double[] lx = new double[length];
					double[] ly = new double[length];
					
					//如果是第一次观测
					if(i==1){
						int j=0;
						for (CorrectDataInfo d : correctDataInfos) {
							depths[j] = Double.parseDouble(d.getDepth());
							cerrors[j] =0;
							j++;
						}
						int lineNum = 6;
						for (int x = 0; x < length; x++) {
							jxl.write.Number depth = new jxl.write.Number(0, lineNum,depths[x]);
							sheet3.addCell(depth);
							//修正数据
							jxl.write.Number cerror = new jxl.write.Number(i, lineNum,cerrors[x]);
							sheet3.addCell(cerror);
							lineNum++;
						}	
					}else{
						//如果不是第一次观测
						int j=0;
						for (CorrectDataInfo d : correctDataInfos) {
							cerrors[j] = Double.parseDouble(d.getError());
							j++;
						}
						int lineNum = 6;
						for (int x = 0; x < length; x++) {
							//修正数据
							jxl.write.Number cerror = new jxl.write.Number(i, lineNum,cerrors[x]);
							sheet3.addCell(cerror);
							lineNum++;
						}
					}
					int j=0;
					for (CorrectDataInfo d : correctDataInfos) {
						depths[j] = Double.parseDouble(d.getDepth());
						A0[j] = Double.parseDouble(d.getA0())*180/3.1415926;
						B0[j] = Double.parseDouble(d.getB0())*180/3.1415926;
						A180[j] = Double.parseDouble(d.getA180())*180/3.1415926;
						B180[j] = Double.parseDouble(d.getB180())*180/3.1415926;
						θAi[j] = Double.parseDouble(d.getThetaX())*180/3.1415926;
						θBi[j] = Double.parseDouble(d.getThetaY())*180/3.1415926;						
						lx[j] = Double.parseDouble(d.getLx());
						ly[j] = Double.parseDouble(d.getLy());
						j++;
					}
					
					int lineNum = 6;
					for (int x = 0; x < length; x++) {
						// 深度
						jxl.write.Number depth = new jxl.write.Number((i-1)*8, lineNum,depths[x]);
						sheet1.addCell(depth);
						
						jxl.write.Number A01 = new jxl.write.Number((i-1)*8+1, lineNum,A0[x]);
						sheet1.addCell(A01);
						jxl.write.Number B01 = new jxl.write.Number((i-1)*8+2, lineNum,B0[x]);
						sheet1.addCell(B01);
						jxl.write.Number A1801 = new jxl.write.Number((i-1)*8+3, lineNum,A180[x]);
						sheet1.addCell(A1801);
						jxl.write.Number B1801 = new jxl.write.Number((i-1)*8+4, lineNum,B180[x]);
						sheet1.addCell(B1801);
						jxl.write.Number θAi1 = new jxl.write.Number((i-1)*8+5, lineNum,θAi[x]);
						sheet1.addCell(θAi1);
						jxl.write.Number θBi1 = new jxl.write.Number((i-1)*8+6, lineNum,θBi[x]);
						sheet1.addCell(θBi1);
						/**待改**/
						jxl.write.Number depth11 = new jxl.write.Number((measureDataTitles.length-1)*8, lineNum,depths[x]);
						sheet1.addCell(depth11);
						jxl.write.Number θAi11 = new jxl.write.Number((measureDataTitles.length-1)*8+i, lineNum,θAi[x]);
						sheet1.addCell(θAi11);					
						//weiyi
						jxl.write.Number depth1 = new jxl.write.Number((measureDataTitles.length-1)*8+measureDataTitles.length+1,lineNum,depths[x]);
						sheet1.addCell(depth1);
						jxl.write.Number lx1 = new jxl.write.Number((measureDataTitles.length-1)*8+i+measureDataTitles.length+1, lineNum,lx[x]);
						sheet1.addCell(lx1);
						
						depth = new jxl.write.Number((i-1)*8+0, lineNum,depths[x]);
						sheet2.addCell(depth);
						jxl.write.Number A02 = new jxl.write.Number((i-1)*8+1, lineNum,A0[x]);
						sheet2.addCell(A02);
						jxl.write.Number B02 = new jxl.write.Number((i-1)*8+2, lineNum,B0[x]);
						sheet2.addCell(B02);
						jxl.write.Number A1802 = new jxl.write.Number((i-1)*8+3, lineNum,A180[x]);
						sheet2.addCell(A1802);
						jxl.write.Number B1802 = new jxl.write.Number((i-1)*8+4, lineNum,B180[x]);
						sheet2.addCell(B1802);
						jxl.write.Number θAi2 = new jxl.write.Number((i-1)*8+5, lineNum,θAi[x]);
						sheet2.addCell(θAi2);
						jxl.write.Number θBi2 = new jxl.write.Number((i-1)*8+6, lineNum,θBi[x]);
						sheet2.addCell(θBi2);
						
						jxl.write.Number depth22 = new jxl.write.Number((measureDataTitles.length-1)*8, lineNum,depths[x]);
						sheet2.addCell(depth22);
						jxl.write.Number θAi22 = new jxl.write.Number((measureDataTitles.length-1)*8+i, lineNum,θBi[x]);
						sheet2.addCell(θAi22);
						//weiyi
						jxl.write.Number depth2 = new jxl.write.Number((measureDataTitles.length-1)*8+measureDataTitles.length+1, lineNum,depths[x]);
						sheet2.addCell(depth2);
						jxl.write.Number ly1 = new jxl.write.Number((measureDataTitles.length-1)*8+i+measureDataTitles.length+1, lineNum,ly[x]);
						sheet2.addCell(ly1);
						
						lineNum++;
					}
						
				}else{
					//不存在修正数据，不做处理
					int aa=0;
					aa++;
				}
				i++;
			}

			// 写入数据
			wwb.write();
			// 关闭文件
			wwb.close();	
		} catch (Exception e) {
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 对于本表中数据的说明，来自哪个工程，哪个工点，等等，说明信息
	 * 
	 * @param sheet
	 * @param baseInfoTitles
	 * @param info
	 * @throws Exception
	 */
	private void createBaseInfo(WritableSheet sheet, String[] baseInfoTitles,
			BaseInfo info,String direction) throws Exception {
		Label label;
		for (int i = 0; i < baseInfoTitles.length; i++) {
			// Label(x,y,z)其中x代表单元格的第x+1列，第y+1行, 单元格的内容是y
			// 在Label对象的子对象中指明单元格的位置和内容
			label = new Label(i, 0, baseInfoTitles[i]);
			// 将定义好的单元格添加到工作表中
			sheet.addCell(label);
		}
		// Log.i("INFO", "创了EXCEL表格！");
		// 填充项目名字
		label = new Label(0, 1, info.getProjectName());
		sheet.addCell(label);
		// 填充工程名字
		label = new Label(1, 1, info.getItemName());
		sheet.addCell(label);
		// 填充钻孔编号
		label = new Label(2, 1, info.getDrillNum());
		sheet.addCell(label);
		
		// 填充深度
		label = new Label(3, 1, info.getDepth());
		sheet.addCell(label);
		// 里程桩号
		label = new Label(4, 1, info.getMark1() + info.getMark2() + "(km)"
				+ info.getMark3() + info.getMark4() + "(km)");
		sheet.addCell(label);
		// 位置描述
		label = new Label(5, 1, info.getLoc());
		sheet.addCell(label);
		/*
		// X坐标
		jxl.write.Number x = new jxl.write.Number(6, 1, Float.parseFloat(info.getX()));
														//注意X，Y不能为空，否则会报错
		sheet.addCell(x);
		// Y坐标
		jxl.write.Number y = new jxl.write.Number(7, 1, Float.parseFloat(info.getY()));
														//注意X，Y可以是小数，所以转浮点型，而不是整型，否则会报错
		sheet.addCell(y);
		*/
		// X坐标
		label = new Label(6, 1, info.getX());
		sheet.addCell(label);
		// Y坐标
		label = new Label(7, 1, info.getY());
		sheet.addCell(label);
		//汇总位移方向
		label = new Label(8, 1, direction);
		sheet.addCell(label);
	}
}
